package com.sutaitech.action;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.sutaitech.common.Constant;
import com.sutaitech.entity.SysUser;
import com.sutaitech.utils.CookieUtil;
import com.sutaitech.utils.ResultVo;

@Controller
public class IndexAction extends BaseAction {
    private static final Logger logger =LoggerFactory.getLogger(IndexAction.class);

    
    /**
	 * 跳转首页
	 */
	@RequestMapping("/")
	public String redirectLogin(HttpServletRequest request, HttpServletResponse response) throws Exception{
		// 检查session中用户是否已登录 如果已经登录 则直接跳转后台
		String userName = CookieUtil.getCookie(request, response, Constant.COOKIE_LOGIN_NAME_KEY);
		if (!StringUtils.isBlank(userName)) {
			// 跳转后台 home
			return "redirect:/home";
		}
		return "/login";
	}
	
	@RequestMapping("/login")
	@ResponseBody
	public ResultVo login(@RequestParam String userName, @RequestParam String password, HttpServletRequest request, HttpServletResponse response){
		ResultVo result = new ResultVo();
		if(StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)){
			result.setStatus(400);
			result.setMessage("账户和密码输入错误");
			return result;
		}
		userName = userName.trim();
		SysUser req = null;
        try {
            req = new SysUser();
            req.setLoginName(userName);
            req.setLoginPwd(password);

            logger.info("userAuthenticationApi.verifyUserByLogin("+userName+" "+password+") result:" + result.toString());
        } catch (Exception e) {
            logger.error("userAuthenticationApi.verifyUserByLogin(req)",e);
            result.setStatus(500);
            result.setMessage("系统服务异常");
            return result;
        }
		if(200==result.getStatus()){
			CookieUtil.saveCookie(response, Constant.COOKIE_MAX_AGE, Constant.COOKIE_LOGIN_NAME_KEY, userName);
			CookieUtil.saveCookie(response, Constant.COOKIE_MAX_AGE, Constant.COOKIE_LOGIN_TYPE_KEY, "console");
		}else{
            String errorCode =  "";
		    if(null!=result.getResult()){
		        errorCode =  (String)result.getResult();
		    }
	        if("3".equals(errorCode) || "4".equals(errorCode)){
                result.setMessage("您的帐号已过期，请联系管理员");
	        }else if("2".equals(errorCode)){
                result.setMessage("密码错误");
            }else{
		        result.setMessage("账户不存在或无系统访问权限");
		    }
		}
		return result;
	}
	
	@RequestMapping("/loginout")
	public String loginout(HttpServletRequest request, HttpServletResponse response){
		String userName = CookieUtil.getCookie(request, response, Constant.COOKIE_LOGIN_NAME_KEY);
		String userType = CookieUtil.getCookie(request, response, Constant.COOKIE_LOGIN_TYPE_KEY);
		String token = CookieUtil.getCookie(request, response, Constant.COOKIE_LOGIN_TOKEN);
		logger.info("user["+userName+","+userType+","+token+"] loginout");
		this.clearCookie(request, response);
		return "redirect:/";
	}
	
	//清楚Cookies
	private void clearCookie(HttpServletRequest request, HttpServletResponse response){
		List<String> key_list = new ArrayList<String>();
		key_list.add(Constant.COOKIE_LOGIN_TOKEN);
		key_list.add(Constant.COOKIE_LOGIN_TYPE_KEY);
		key_list.add(Constant.COOKIE_LOGIN_NAME_KEY);	
		CookieUtil.clearCookie(request, response, key_list);
	}
	
    
    @RequestMapping("/home")
	public String index() {
		return "index";
	}
    
   
}
